<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
	content="width=device-width,initial-scale=1 user-scalable=0">
<link rel="stylesheet" href="<%=basePath%>assets/css/public.css">
<link rel="stylesheet" href="<%=basePath%>assets/css/page.css">
<link rel="stylesheet"
	href="<%=basePath%>assets/font-awesome-4.7.0/css/font-awesome.min.css">
<link rel="stylesheet"
	href="<%=basePath%>assets/css/idangerous.swiper.css">
<link rel="stylesheet" type="text/css"
	href="<%=basePath%>assets/css/globle.css" />
<meta name="viewport" content="width=device-width,initial-scale=1 user-scalable=0">
<title>发布</title>
<link rel="stylesheet" href="<%=basePath%>assets/css/public.css">
<link rel="stylesheet" href="<%=basePath%>assets/css/idangerous.swiper.css">
<link rel="stylesheet" type="text/css" href="<%=basePath%>assets/css/globle.css" />
<script src="<%=basePath%>assets/js/jquery-1.8.3.min.js"></script>
<script src="<%=basePath%>assets/js/fontSize.js"></script>
<script src="<%=basePath%>assets/js/webuploader.min.js"></script>
<script src="<%=basePath%>assets/js/diyUpload.js"></script>
<script src="<%=basePath%>/assets/js/newToast/newToast.js"></script>
<link rel="stylesheet" href="<%=basePath%>/assets/js/newToast/newToast.css">
<link rel="stylesheet" href="<%=basePath%>/assets/imgTools/helmet.css">
<script src="<%=basePath%>/assets/layer/mobile/layer.js"></script>

<style>
html {
	width: 100%;
	height: 100%
}

body {
	padding-top: 1.6rem;
}

header {
	background: #f1f1f1
}

.title {
	font-size: 0.4rem;
	line-height: 0.8rem;
	text-align: center;
	padding: 0 0.6rem
}

header a {
	float: left;
	width: 0.3rem;
	height: 0.8rem;
	font-size: 0.3rem;
	line-height: 0.8rem;
	padding: 0 0.3rem
}

.biaotitianxie {
	height: 0.8rem;
	line-height: 0.6rem;
	width: 100%;
	border-bottom: 1px solid #f1f1f1;
	font-size: 0.24rem;
	display: block;
}

.neirongtianxie {
	height: 1.6rem;
	width: 100%;
	border: none;
	font-size: 0.24rem;
	line-height: 0.4rem;
	padding-top: 10px;
	display: block;
}

.upload-ul{
	display: block;
}

.jiage {
	font-size: 0.24rem;
	line-height: 1.0rem;
	border-bottom: 1px solid #f1f1f1;
	width: 100%;
	height: 0.8rem
}

.fenlei {
	font-size: 0.24rem;
	line-height: 1.0rem;
	border-bottom: 1px solid #f1f1f1;
	width: 100%;
	height: 0.8rem;
	color: #aaaaaa;
	background-color: #fff;
}

.jiagekuang, .fenleikuang {
	width: 100%;
	height: 0.6rem;
	background: #f1f1f1;
	display: none
}

.jiagekuang input {
	width: 100%;
	height: 100%;
	line-height: 100%;
}

.jiage a, .fenlei a {
	width: 10%;
	text-align: right;
	color: #aaaaaa
}
.upload-btn {
    padding: 14px 0px;
    color: #fff;
    margin: 0; 
    width: 100%;
    text-align: center;
}

.aside2{
	display: none;
}

.touch {
	background-color: #ddd;
}

.img-list {
	margin: 10px 5px;
}

.img-list li {
/* 	position: relative; */
/* 	display: inline-block; */
/* 	width: 100px; */
/* 	height: 100px; */
/* 	margin: 5px 5px 20px 5px; */
/* 	border: 1px solid rgb(100, 149, 198); */
/* 	background: #fff no-repeat center; */
	background-size: cover;
}

.progress {
	position: absolute;
	width: 100%;
	height: 20px;
	line-height: 20px;
	bottom: 0;
	left: 0;
	background-color: rgba(100, 149, 198, .5);
}

.progress span {
	display: block;
	width: 0;
	height: 100%;
	background-color: rgb(100, 149, 198);
	text-align: center;
	color: #FFF;
	font-size: 13px;
}
.progress .del{
    position: absolute;
    top: -64px;
    right: 2px;
    background-color: rgba(26,26,25,0.7);
    display: block;
    line-height: 14px;
    width: 14px;
    height: 14px;
}
.upload-pick{
	position: relative;
}

</style>
<script>
	$(function() {
		$('body').click(function() {
			$('.jiagekuang').slideUp();
			$('.fenleikuang').slideUp();

		});
		$('.jiageBox').click(function() {
			event.stopPropagation();
		});
		$('.jiageanniu').click(function() {

			$('.jiagekuang').slideDown()
		});
		$('.fenleiBox').click(function() {
			event.stopPropagation();
		});
		$('.fenleianniu').click(function() {
			$('.fenleikuang').slideDown()
		});
		
		$('.sell a').css('color',"#FF3F25");
		$('.buy').click(function(){
			$('.aside1').hide();
			$('.aside2').show();
			$('.buy').addClass('active');
			$('.sell').removeClass('active');
			$('.buy a').css('color',"#FF3F25");
			$('.sell a').css('color',"");
		});
		$('.sell').click(function(){
			$('.aside2').hide();
			$('.aside1').show();
			$('.sell').addClass('active');
			$('.buy').removeClass('active');
			$('.sell a').css('color',"#FF3F25");
			$('.buy a').css('color',"");
		});
	})
</script>
</head>
<body>
	<input id="basePath" type="hidden" value="<%=basePath%>">
	<div class="header">
		<!-- 返回按钮 -->
		<a class=returnInfo href="<%=basePath%>app/getUsedGoodsList"><i class="fa fa-angle-left"></i></a> 发布
	</div>
	<div class="find_nav">
		<div class="find_nav_left">
			<div class="find_nav_list" id="pagenavi1">
				<ul>
					<li class="sell active"><a>出售</a></li>
					<li class="buy"><a>求购</a></li>
				</ul>
			</div>
		</div>
	</div>
	<div class="content aside1">
		<input id="goodsName" type="text" placeholder="标题 品类品牌型号都是买家喜欢搜索的"
			class="biaotitianxie">
		<textarea id="goodsIntro" placeholder="描述一下宝贝的细节"
			class="neirongtianxie"></textarea>
		<div>
<!-- 			<ul class="upload-ul clearfix"> -->
<!-- 				<li class="upload-pick"> -->
<!-- 					<div class="webuploader-container clearfix" id="goodsUpload"></div> -->
<!-- 					<input id="imgPath" type="hidden" value=""> -->
<!-- 				</li> -->
<!-- 			</ul> -->
			<ul class="img-list upload-ul clearfix">
				<li class="upload-pick">
					<input type="file" style="display: none" id="choose" accept="image/*" multiple>
					<a id="upload" style="display:block;width: 115px;height: 100px"></a>
					<input id="imgPath" type="hidden" value="">
				</li>
			</ul>
		</div>
		<div class="jiageBox">
			<div class="jiage">
				<input id="goodsPrice" type="number" placeholder="请输入预期出售价格" step="0.01" >
			</div>
		</div>
		<div class="jiageBox">
			<div class="jiage">
				<input id="goodsQuondamPrice" type=number placeholder="请输入原价" step="0.01">
			</div>
		</div>
		<div class="fenleiBox">
			<div>
				<select class="fenlei" id="goodsType"></select>
			</div>
			<!--     <div class="fenleikuang"></div> -->
		</div>
		<p>
			<a id="sellGoods" class="upload-btn" href="javascript:;"
				style="background-color: #FF3F25;">确定发布</a>
		</p>
	</div>

	<div class="content aside2">
		<input id="buyName" type="text" placeholder="请输入你想购买的商品的标题"
			class="biaotitianxie">
		<textarea id="buyIntro" placeholder="描述一下宝贝的细节"
			class="neirongtianxie"></textarea>
		<div>
			<ul class="upload-ul clearfix">
				<li class="upload-pick">
					<div class="webuploader-container clearfix" id="buyUpload"></div>
					<input id="buyImgPath" type="hidden" value="">
				</li>
			</ul>
		</div>
		<div class="jiageBox">
			<div class="jiage">
				<input id="buyPrice" type="number" placeholder="请输入预期购买价格" step="0.01">
			</div>
		</div>
		<div class="jiageBox">
			<div class="jiage">
				<input id="buyQuondamPrice" type="number" placeholder="请输入原价" step="0.01">
			</div>
		</div>
		<div class="fenleiBox">
			<div>
				<select class="fenlei" id="buyGoodsType"></select>
			</div>
			<!--     <div class="fenleikuang"></div> -->
		</div>
		<p>
			<a id="buyGoods" class="upload-btn" href="javascript:;"
				style="background-color: #FF3F25;">确定发布</a>
		</p>
	</div>
	


	<script>
		$(function() {
			//上传图片
			var $tgaUpload = $('#goodsUpload').diyUpload({
				url : $("#basePath").val() + 'app/uploadUsedImg',
				success : function(data) {
					var photoStr = $("#imgPath").val();
					if (photoStr == "") {
						$("#imgPath").val(data.photoStr);
					} else {
						$("#imgPath").val(photoStr + ',' + data.photoStr);
					}
				},
				error : function(err) {
				},
				buttonText : '',
				accept : {
					title : "Images",
					extensions : 'gif,jpg,jpeg,bmp,png'
				},
				thumb : {
					width : 120,
					height : 90,
					quality : 100,
					allowMagnify : true,
					crop : true,
					type : "image/jpeg"
				},
				auto : true
			});

			//获取分类
			$.ajax({
				url : $("#basePath").val() + "app/getGoodsClassifyList",
				timeout : 300000,
				dataType : "json",
				type : "post",
				data : {},
				success : function(data) {
					var html = "";
					$.each(data, function(i, item) {
						html += '<option value ="'+item.cassifyId+'">'
								+ item.cassifyName + '</option>' +

								'</opting>';
					})
					$(".fenlei").html(html);
				}
			})

		});
		//确定发布
		$("#sellGoods").click(function() {
			var reg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
			if ($("#goodsName").val() == "" || $("#goodsName").val() == null) {
				layer.open({
				    content: '请输入标题'
			    	,skin: 'msg'
				    ,time: 2 //2秒后自动关闭
			  	});
				return false;
			} else if ($("#goodsIntro").val() == "" || $("#goodsIntro").val() == null) {
				layer.open({
				    content: '请输入描述'
			    	,skin: 'msg'
				    ,time: 2 //2秒后自动关闭
			  	});
				return false;
			} else if ($("#goodsPrice").val() == "" || $("#goodsPrice").val() == null) {
				layer.open({
				    content: '请输入价格'
			    	,skin: 'msg'
				    ,time: 2 //2秒后自动关闭
			  	});
				return false;
			} else if (!reg.test($("#goodsPrice").val())) {
				layer.open({
				    content: '输入的价格不合法'
			    	,skin: 'msg'
				    ,time: 2 //2秒后自动关闭
			  	});
				return false;
			} 
// 			else if ($("#goodsQuondamPrice").val() == "" || $("#goodsQuondamPrice").val() == null) {
// 				layer.open({
// 				    content: '请输入原价'
// 			    	,skin: 'msg'
// 				    ,time: 2 //2秒后自动关闭
// 			  	});
// 				return false;
// 			} 
			else if (!reg.test($("#goodsQuondamPrice").val())) {
				layer.open({
				    content: '输入的原价不合法'
			    	,skin: 'msg'
				    ,time: 2 //2秒后自动关闭
			  	});
				return false;
			} else if ($("#goodsType").val() == "" || $("#goodsType").val() == null) {
				layer.open({
				    content: '请选择分类'
			    	,skin: 'msg'
				    ,time: 2 //2秒后自动关闭
			  	});
				return false;
			} else if ($("#imgPath").val() == "" || $("#imgPath").val() == null) {
				layer.open({
				    content: '请至少上传一张图片'
			    	,skin: 'msg'
				    ,time: 2 //2秒后自动关闭
			  	});
				return false;
			} else {
				$.ajax({
					url : $("#basePath").val() + "app/addUsedGoods",
					timeout : 300000,
					dataType : "json",
					type : "post",
					data : {
						"goodsName" : $("#goodsName").val(),
						"goodsIntro" : $("#goodsIntro").val(),
						"goodsPrice" : $("#goodsPrice").val(),
						"goodsQuondamPrice" : $("#goodsQuondamPrice").val(),
						"classifyId1" : $("#goodsType").val(),
						"photoStr" : $("#imgPath").val(),
						"goodsIdentifying" : 2
					},
					success : function(data) {
						if (data.state = 1) {
							window.location.href = $("#basePath").val() + "app/getUsedGoodsInfo?goodsId="+ data.goodsId;
						} else {
							alert(data.msg);
						}
					},
					error : function(data) {
						alert("网络错误");
					}
				})
			}
		});
		
		//上传购买图片
		var $buyUpload = $('#buyUpload').diyUpload({
			url : $("#basePath").val() + 'app/uploadUsedImg',
			success : function(data) {
				var photoStr = $("#imgPath").val();
				if (photoStr == "") {
					$("#buyImgPath").val(data.photoStr);
				} else {
					$("#buyImgPath").val(photoStr + ',' + data.photoStr);
				}
			},
			error : function(err) {
			},
			buttonText : '',
			accept : {
				title : "Images",
				extensions : 'gif,jpg,jpeg,bmp,png'
			},
			thumb : {
				width : 120,
				height : 90,
				quality : 100,
				allowMagnify : true,
				crop : true,
				type : "image/jpeg"
			},
			auto : true
		});
		
		//确定发布
		$("#buyGoods").click(function() {
			var reg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
			if ($("#buyName").val() == "" || $("#buyName").val() == null) {
				layer.open({
				    content: '请输入标题'
			    	,skin: 'msg'
				    ,time: 2 //2秒后自动关闭
			  	});
				return false;
			} else if ($("#buyIntro").val() == "" || $("#buyIntro").val() == null) {
				layer.open({
				    content: '请输入描述'
			    	,skin: 'msg'
				    ,time: 2 //2秒后自动关闭
			  	});
				return false;
			} else if ($("#buyPrice").val() == "" || $("#buyPrice").val() == null) {
				layer.open({
				    content: '请输入价格'
			    	,skin: 'msg'
				    ,time: 2 //2秒后自动关闭
			  	});
				return false;
			} else if (!reg.test($("#buyPrice").val())) {
				layer.open({
				    content: '输入的价格不合法'
			    	,skin: 'msg'
				    ,time: 2 //2秒后自动关闭
			  	});
				return false;
			} 
// 			else if ($("#buyQuondamPrice").val() == "" || $("#buyQuondamPrice").val() == null) {
// 				layer.open({
// 				    content: '请输入原价'
// 			    	,skin: 'msg'
// 				    ,time: 2 //2秒后自动关闭
// 			  	});
// 				return false;
// 			} 
			else if (!reg.test($("#buyQuondamPrice").val())) {
				layer.open({
				    content: '输入的原价不合法'
			    	,skin: 'msg'
				    ,time: 2 //2秒后自动关闭
			  	});
				return false;
			} else if ($("#buyGoodsType").val() == "" || $("#buyGoodsType").val() == null) {
				layer.open({
				    content: '请选择分类'
			    	,skin: 'msg'
				    ,time: 2 //2秒后自动关闭
			  	});
				return false;
			} else if ($("#buyImgPath").val() == "" || $("#buyImgPath").val() == null) {
				layer.open({
				    content: '请至少上传一张图片'
			    	,skin: 'msg'
				    ,time: 2 //2秒后自动关闭
			  	});
				return false;
			} else {
				$.ajax({
					url : $("#basePath").val() + "app/addUsedGoods",
					timeout : 300000,
					dataType : "json",
					type : "post",
					data : {
						"goodsName" : $("#buyName").val(),
						"goodsIntro" : $("#buyIntro").val(),
						"goodsPrice" : $("#buyPrice").val(),
						"goodsQuondamPrice" : $("#buyQuondamPrice").val(),
						"classifyId1" : $("#buyGoodsType").val(),
						"photoStr" : $("#buyImgPath").val(),
						"goodsIdentifying" : 3
					},
					success : function(data) {
						if (data.state = 1) {
							window.location.href = $("#basePath").val() + "app/getUsedGoodsInfo?goodsId="+ data.goodsId;
						} else {
							alert(data.msg);
						}
					},
					error : function(data) {
						alert("网络错误");
					}
				})
			}
		});
		
		
		var filechooser = document.getElementById("choose");
		//用于压缩图片的canvas
		var canvas = document.createElement("canvas");
		var ctx = canvas.getContext('2d');
		//瓦片canvas
		var tCanvas = document.createElement("canvas");
		var tctx = tCanvas.getContext("2d");
		var maxsize = 100 * 1024;
		$("#upload").on("click", function() {
		      filechooser.click();
		}).on("touchstart", function() {
		      $(this).addClass("touch")
		}).on("touchend", function() {
		      $(this).removeClass("touch")
		});
		filechooser.onchange = function() {
			if(this.files[0].size == 0){
				return;
			}
		  	if (!this.files.length) return;
		  	var files = Array.prototype.slice.call(this.files);
		  	if (files.length > 9) {
		    	alert("最多同时只可上传9张图片");
		    	return;
		  	}
		  	files.forEach(function(file, i) {
			    if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return;
			    var reader = new FileReader();
			    var li = document.createElement("li");
				//获取图片大小
//	 		    var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
			    li.innerHTML = '<div class="progress"><span></span></div><div class="size"></div>';
			    $(".img-list").prepend($(li));
			    reader.onload = function() {
			      	var result = this.result;
			      	var img = new Image();
			      	img.src = result;
			      	$(li).css("background-image", "url(" + result + ")");
			      	//如果图片大小小于100kb，则直接上传
			      	if (result.length <= maxsize) {
			        	img = null;
			        	upload(result, file.type, $(li));
			        	return;
			      	}
				  	//图片加载完毕之后进行压缩，然后上传
			      	if (img.complete) {
			        	callback();
			     	} else {
			        	img.onload = callback;
			      	}
			      	function callback() {
				        var data = compress(img);
				        upload(data, file.type, $(li));
				        img = null;
			      	}
			    };
			    reader.readAsDataURL(file);
		  })
		};
		
		//图片上传，将base64的图片转成二进制对象，塞进formdata上传
		function upload(basestr, type, $li) {
		  	var text = window.atob(basestr.split(",")[1]);
		    var buffer = new Uint8Array(text.length);
		    var pecent = 0, loop = null;
		    for (var i = 0; i < text.length; i++) {
		    	buffer[i] = text.charCodeAt(i);
		    }
		    var blob = getBlob([buffer], type);
		    var xhr = new XMLHttpRequest();
		    var formdata = getFormData();
		    formdata.append('imagefile', blob);
		    xhr.open('post', '<%=basePath%>app/uplondImg');
		    xhr.onreadystatechange = function() {
		      	if (xhr.readyState == 4 && xhr.status == 200) {
		        	var jsonData = JSON.parse(xhr.responseText);
			        var text = jsonData.state == 1 ? '上传成功' : '上传失败';
			        console.log(text + '：' + jsonData.photoStr);
			        clearInterval(loop);
			        
			        if($("#imgPath").val() == ""){
			        	$("#imgPath").val(jsonData.photoStr);
			        }else{
			        	var imgPath = $("#imgPath").val() + "," +jsonData.photoStr;
			        	$("#imgPath").val(imgPath);
			        }
			        
			        //当收到该消息时上传完毕
			        $li.find(".progress span").animate({'width': "100%"}, pecent < 95 ? 200 : 0, function() {
			          $(this).html(text + '<span class="del" onclick="delThisImg(this)"><i class="fa fa-close"></i></span>');
			        });
//	 		        if (!imagedata.photoStr) return;
//	 		        $(".pic-list").append('<a href="' + imagedata.photoStrv + '">' + imagedata.name + '（' + imagedata.size + '）<img src="' + jsonData.photoStr + '" /></a>');
		      	}
		    };
		    //数据发送进度，前50%展示该进度
		    xhr.upload.addEventListener('progress', function(e) {
		      	if (loop) return;
			      	pecent = ~~(100 * e.loaded / e.total) / 2;
			      	$li.find(".progress span").css('width', pecent + "%");
			      	if (pecent == 50) {
		        	mockProgress();
		      }
		    }, false);
		    //数据后50%用模拟进度
		    function mockProgress() {
		      	if (loop) return;
		      		loop = setInterval(function() {
		        	pecent++;
		        	$li.find(".progress span").css('width', pecent + "%");
		        	if (pecent == 99) {
		          		clearInterval(loop);
		        	}
		      	}, 100)
	    	}
		    xhr.send(formdata);
		}

		function delThisImg(obj){
			$(obj).parent().parent().parent().remove();
		}
		
		//使用canvas对大图片进行压缩
	  	function compress(img) {
		    var initSize = img.src.length;
		    var width = img.width;
		    var height = img.height;
		    //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
		    var ratio;
		    if ((ratio = width * height / 4000000) > 1) {
		      	ratio = Math.sqrt(ratio);
		      	width /= ratio;
		      	height /= ratio;
		    } else {
		      	ratio = 1;
		    }
		    canvas.width = width;
		    canvas.height = height;
			//铺底色
		    ctx.fillStyle = "#fff";
		    ctx.fillRect(0, 0, canvas.width, canvas.height);
		    //如果图片像素大于100万则使用瓦片绘制
		    var count;
		    if ((count = width * height / 1000000) > 1) {
		      	count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
				//计算每块瓦片的宽和高
		      	var nw = ~~(width / count);
		      	var nh = ~~(height / count);
		      	tCanvas.width = nw;
		      	tCanvas.height = nh;
		      	for (var i = 0; i < count; i++) {
		        	for (var j = 0; j < count; j++) {
			          	tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
			          	ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
		        	}
		      	}
		    } else {
		      	ctx.drawImage(img, 0, 0, width, height);
		    }
		    //进行最小压缩
		    var ndata = canvas.toDataURL('image/jpeg', 0.2);
		    console.log('压缩前：' + initSize);
		    console.log('压缩后：' + ndata.length);
		    console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
		    tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
		    return ndata;
	  	}
		  
	  	/**
		* 获取blob对象的兼容性写法
		* @param buffer
		* @param format
		* @returns {*}
	   	*/
	  	function getBlob(buffer, format) {
		    try {
		      	return new Blob(buffer, {type: format});
		    } catch (e) {
		      	var bb = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
		      	buffer.forEach(function(buf) {
		        	bb.append(buf);
		      	});
		      	return bb.getBlob(format);
		    }
	  	}
	  	/**
		* 获取formdata
	   	*/
	  	function getFormData() {
	    	var isNeedShim = ~navigator.userAgent.indexOf('Android')
		        && ~navigator.vendor.indexOf('Google')
		        && !~navigator.userAgent.indexOf('Chrome')
		        && navigator.userAgent.match(/AppleWebKit\/(\d+)/).pop() <= 534;
		    return isNeedShim ? new FormDataShim() : new FormData()
	  	}
	  	/**
	   	* formdata 补丁, 给不支持formdata上传blob的android机打补丁
	   	* @constructor
	  	*/
	  	function FormDataShim() {
			console.warn('using formdata shim');
		    var o = this,
	        parts = [],
	        boundary = Array(21).join('-') + (+new Date() * (1e16 * Math.random())).toString(36),
	        oldSend = XMLHttpRequest.prototype.send;
	    	this.append = function(name, value, filename) {
	      		parts.push('--' + boundary + '\r\nContent-Disposition: form-data; name="' + name + '"');
	      		if (value instanceof Blob) {
	        		parts.push('; filename="' + (filename || 'blob') + '"\r\nContent-Type: ' + value.type + '\r\n\r\n');
	        		parts.push(value);
	      		}else {
	        		parts.push('\r\n\r\n' + value);
	      		}
	      		parts.push('\r\n');
	    	};
		    // Override XHR send()
		    XMLHttpRequest.prototype.send = function(val) {
		    	var fr,data,oXHR = this;
		      	if (val === o) {
			        // Append the final boundary string
			        parts.push('--' + boundary + '--\r\n');
			        // Create the blob
			        data = getBlob(parts);
			        // Set up and read the blob into an array to be sent
			        fr = new FileReader();
			        fr.onload = function() {
			        	oldSend.call(oXHR, fr.result);
			        };
			        fr.onerror = function(err) {
			        	throw err;
			        };
			        fr.readAsArrayBuffer(data);
			        // Set the multipart content type and boudary
			        this.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
			        XMLHttpRequest.prototype.send = oldSend;
		      	}else {
		        	oldSend.call(this, val);
		      	}
	    	};
	  	}
	</script>
</body>
</html>